--local Util = require("common.Util")
local Msg = require("core.Msg")
local ObjHuman = require("core.ObjHuman")
local GridLogic = require("bag.GridLogic")
local MailDefine = require("mail.Define")
local ItemDefine = require("bag.ItemDefine")

local Grid = require("bag.Grid")
local BagLogic = require("bag.BagLogic")
local InnerDataDefine = require("innerdata.Define")
local InnerDataManagerFL = require("innerdata.InnerDataManagerFL")

function CreateNewMailForUser(uuid, title, content, gridList)
    if title == "" then
        return MailDefine.ERR_SENDMAIL_NOTITLE
    end

    if #gridList > 6 then
        return MailDefine.ERR_SENDMAIL_ATTACHMENTMAX
    end

    local nMsg = Msg.lw.LW_SENDMAIL
    nMsg.title = title 
    nMsg.content = content
    nMsg.itemlist[0] = 0
    if gridList then
        for i = 1, #gridList do
            nMsg.itemlist[0] = i
            GridLogic.makeGrid(gridList[i], nMsg.itemlist[i], nil, nil)
        end
    end
    nMsg.uuid = uuid
    Msg.send2world(nMsg, "")
    return true
end

function OnAttachMent(human, oType, oMsg)
    local mailData = oMsg.mail
    if not mailData then
        return false
    end
    local nRetMsg = {result = 0, mailid = mailData.mailID}

    if mailData.items then
    end

    local needSpace = 0
    local yinliangAdd = 0

    for i = 1, mailData.items[0] do
        local nData = mailData.items[i]
        if nData then
            if ItemDefine.is_spobj[nData.id] ~= true then
                needSpace = needSpace + 1
            elseif ItemDefine.spobj.yinliang[nData.id] then
                yinliangAdd = yinliangAdd + nData.cnt
            end
        end
    end

    if yinliangAdd > 0 and ObjHuman.canAddYinliang(human, yinliangAdd) ~= true then
        nRetMsg.result = -1
    end

    local nLeftBag = BagLogic.getLeftGrids(human)
    if needSpace > nLeftBag then
        nRetMsg.result = -2
    end

    if nRetMsg.result == 0 then
        for i = 1, mailData.items[0] do
            local nData = mailData.items[i]
            if nData then
                if nData.cnt > 0 and  ItemDefine.isValidId(nData.id) then
                    local nGridData = Grid.create(nil, nData.id, nData.cnt, nData.bind or 0)
                    BagLogic.addItemByGrid(human, nil, nGridData, "mail")
                end
            end
        end
    end
    InnerDataManagerFL.Send2WInnerData(human, InnerDataDefine.INNERDATA_TYPE_MAIL, nRetMsg)
end

InnerDataManagerFL.Register(InnerDataDefine.INNERDATA_TYPE_MAIL, OnAttachMent)
